import 'package:flutter/material.dart';
import 'bill.dart';

class NextPage extends StatefulWidget {
  const NextPage({Key? key, required this.addBill}) : super(key: key);

  final Function(Bill) addBill;

  @override
  State<NextPage> createState() => _NextPageState();
}

class _NextPageState extends State<NextPage> {
  String currentAction = '支出'; // 初始操作为支出
  IconData currentIcon = Icons.remove_circle_outline; // 初始图标为支出图标
  List<IconData> expenseIcons = [
    Icons.remove_circle_outline, // 支出图标
    Icons.account_balance_wallet, // 钱包图标
  ];
  
  List<IconData> incomeIcons = [
    Icons.add_circle_outline, // 收入图标
    Icons.attach_money, // 附加金钱图标
  ];

  List<IconData> icons = []; // 默认为空，将在initState中初始化

  final _amountController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _noteController = TextEditingController();
  DateTime _selectedDate = DateTime.now(); // 默认日期

  @override
  void initState() {
    super.initState();
    icons = currentAction == '支出' ? expenseIcons : incomeIcons;
  }

  void handleAction(String action) {
    setState(() {
      currentAction = action;
      if (action == '支出') {
        currentIcon = Icons.remove_circle_outline;
        icons = expenseIcons;
      } else if (action == '收入') {
        currentIcon = Icons.add_circle_outline;
        icons = incomeIcons;
      }
    });
  }

  String getIconIntro(IconData icon) {
    switch (icon) {
      case Icons.remove_circle_outline:
        return '支出';
      case Icons.account_balance_wallet:
        return '钱包';
      case Icons.add_circle_outline:
        return '收入';
      case Icons.attach_money:
        return '金钱';
      default:
        return '';
    }
  }

  void handleIconClick(IconData icon) {
    setState(() {
      currentIcon = icon;
      _descriptionController.text = getIconIntro(icon); // 设置description的值
    });
    showBottomSheet(); // 显示记账表单
  }

  void showBottomSheet() {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true, // 允许滚动控制
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, StateSetter setState) {
          return Container(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            height: 400,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                TextField(
                  controller: _amountController,
                  decoration: InputDecoration(labelText: 'Amount'),
                ),
                TextField(
                  controller: _descriptionController,
                  decoration: InputDecoration(labelText: 'Description'),
                ),
                TextField(
                  controller: _noteController,
                  decoration: InputDecoration(labelText: 'Note'),
                ),
                GestureDetector(
                  onTap: () async {
                    final DateTime? selectedDate = await showDatePicker(
                      context: context,
                      initialDate: _selectedDate,
                      firstDate: DateTime(2000),
                      lastDate: DateTime.now(),
                    );
                    if (selectedDate != null) {
                      setState(() {
                        _selectedDate = selectedDate;
                      });
                    }
                  },
                  child: Container(
                    margin: const EdgeInsets.all(8.0),
                    alignment: Alignment.center,
                    height: 40,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                    ),
                    child: Text(
                      _selectedDate.toString().split(' ')[0], // 显示日期
                      style: TextStyle(fontSize: 16),
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    String amount = _amountController.text;
                    String description = _descriptionController.text;
                    String note = _noteController.text;
                    if (amount.isEmpty || description.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Please fill all fields')),
                      );
                      return;
                    }
                    Bill newBill = Bill(
                      amount: amount,
                      description: description,
                      note: note,
                      date: _selectedDate,
                    );
                    widget.addBill(newBill); // Add bill to the home page
                    Navigator.pop(context);
                    Navigator.pop(context);
                  },
                  child: Text('Save'),
                ),
              ],
            ),
          );
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center, // 居中显示
          children: [
            Container(
              constraints: BoxConstraints.tightFor(width: 60, height: 40), // 固定大小
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.5), // 灰色偏白的背景
                borderRadius: BorderRadius.circular(100), // 圆角
                border: Border.all(color: Colors.grey), // 边框
              ),
              child: TextButton(
                onPressed: () => handleAction('支出'),
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(const EdgeInsets.symmetric(vertical: 8)),
                ),
                child: Text('支出'), // 原来的字体颜色
              ),
            ),
            const SizedBox(width: 8.0), // 添加按钮之间的间隔
            Container(
              constraints: BoxConstraints.tightFor(width: 60, height: 40), // 固定大小
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.5), // 灰色偏白的背景
                borderRadius: BorderRadius.circular(100), // 圆角
                border: Border.all(color: Colors.grey), // 边框
              ),
              child: TextButton(
                onPressed: () => handleAction('收入'),
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(const EdgeInsets.symmetric(vertical: 8)),
                ),
                child: Text('收入'), // 原来的字体颜色
              ),
            ),
          ],
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              children: icons.map((icon) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      ElevatedButton(
                        onPressed: () => handleIconClick(icon),
                        child: Icon(icon),
                      ),
                      Text(getIconIntro(icon), style: TextStyle(fontSize: 12, overflow: TextOverflow.clip)), // Display icon intro
                    ],
                  ),
                );
              }).toList(),
            ),

          ],
        ),
      ),
    );
  }
}